home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2273 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: news.magi.com!news!news.magi.com
  2. From: nredding@magi.com (Neil Redding)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Fri, 19 Jan 1996 23:28:30 -0500
  6. Organization: Magi Data Consulting
  7. Message-ID: <nredding-1901962328300001@magi05p71.magi.com>
  8. References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com> <nredding-1901962245370001@magi04p72.magi.com>
  9. NNTP-Posting-Host: magi05p71.magi.com
  10.  
  11. In article <nredding-1901962245370001@magi04p72.magi.com>,
  12. nredding@magi.com (Neil Redding) wrote:
  13.  
  14.  
  15. >If n is a power of 2, repeatedly multiplying n by 2 will eventually give you
  16. >2**32 == 0 when it overflows. Also shifting left one bit ( n<<1) is the same
  17. >as multiplying by 2.
  18. >Thus:
  19. >
  20. >
  21. >Boolean IsPowerOfTwo( unsigned long n )
  22. >{
  23. >   short k = 31;
  24. >   if ( n == 0 )
  25. >       return false;
  26. >  while ( k--  > 0 )
  27. >        if ( (n <<= 1 ) == 0 )
  28. >              return true;
  29. >  return false;
  30. >}
  31. >
  32. >-- 
  33. Sorry...I realized just after sending this that it is also incorrect.
  34. Robert Fry's solution
  35. looks good though.
  36.  
  37. -- 
  38. Neil Redding
  39. Ottawa, Canada
  40.